package com.jianz.campus_markets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jianz.campus_markets.domain.ResponseResult;
import com.jianz.campus_markets.domain.entity.SysMenu;
import com.jianz.campus_markets.mapper.SysMenuMapper;
import com.jianz.campus_markets.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author jianz
 * @since 2023-11-27
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public ResponseResult load() {

        List<SysMenu> sysMenus = getBaseMapper().selectList(null);

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        Collection<HandlerMethod> methods = handlerMethods.values();

        for (HandlerMethod handlerMethod : methods) {
            Method method = handlerMethod.getMethod();

            GetMapping annotation = method.getAnnotation(GetMapping.class);
            System.out.println(annotation);

        }


        return ResponseResult.okResult(sysMenus);
    }

    @Override
    public List<String> selectPermsByUserId(Long id) {
        //根据用户id查询用户的权限信息。用户id为id代表超级管理员，如果是管理员就返回所有的权限
        if(id == 1L){
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
            //查询条件是permissions中需要有状态为正常的权限。
            wrapper.eq(SysMenu::getStatus,0);
            //查询条件是permissions中需要未被删除的权限的权限
            List<SysMenu> menus = list(wrapper);
            List<String> perms = menus.stream()
                    .map(SysMenu::getPerms)
                    .collect(Collectors.toList());
            return perms;
        }

        //如果不是管理员就返回对应用户所具有的权限
        List<String> otherPerms = getBaseMapper().selectPermsByOtherUserId(id);
        System.out.println(otherPerms);
        return otherPerms;
    }
}
